package main

import (
	"bytes"
	"common/version"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"io"
	"strings"
)

type CheckUpgradeReq struct {
	Version  string          `json:"version" form:"version" binding:"required"`
	CommitId string          `json:"commit_id" form:"commit_id" binding:"required"`
	Arch     string          `json:"arch" form:"arch" binding:"required"`
	Os       string          `json:"os" form:"os" binding:"required"`
	Env      string          `json:"env" form:"env" binding:"required"`
	NodeId   string          `json:"node_id" form:"node_id" binding:"required"`
	DeviceId string          `json:"device_id" form:"device_id" binding:"omitempty"`
	Ver      version.Version `json:"-"`
}

// 查询是否需要更新
func (s *Server) checkUpgrade(ctx *gin.Context) {
	var err error
	defer func() {
		if err != nil {
			s.errorJson(ctx, err)
		}
	}()
	req := CheckUpgradeReq{}
	if err = ctx.Bind(&req); err != nil {
		return
	}
	req.Ver, err = version.FromString(req.Version)
	if err != nil {
		return
	}
	req.Arch = strings.ToLower(req.Arch)
	req.Os = strings.ToLower(req.Os)
	pkgItem, ok := s.pkgList.upgrade(&req)
	if !ok {
		s.successJson(ctx, gin.H{"upgrade": false})
	} else {
		s.successJson(ctx, gin.H{
			"upgrade":      true,
			"version":      pkgItem.Version,
			"download_url": pkgItem.DownloadUrl,
			"size":         pkgItem.Size,
			"md5":          pkgItem.Md5,
			"uuid":         pkgItem.UUID,
		})
	}
}

type LatestReq struct {
	Arch string `json:"arch" form:"arch" binding:"required"`
	Os   string `json:"os" form:"os" binding:"required"`
	Env  string `json:"env" form:"env" binding:"required"`
}

// 获取最新程序包信息
func (s *Server) latest(ctx *gin.Context) {
	var err error
	defer func() {
		if err != nil {
			s.errorJson(ctx, err)
		}
	}()
	req := LatestReq{}
	if err = ctx.Bind(&req); err != nil {
		return
	}
	fmt.Println(req)
	pkgItem := s.pkgList.latest(&req)
	if pkgItem == nil {
		s.errorJson(ctx, errors.New("no node package"))
	} else {
		s.successJson(ctx, gin.H{
			"version":      pkgItem.Version,
			"download_url": pkgItem.DownloadUrl,
			"size":         pkgItem.Size,
			"md5":          pkgItem.Md5,
			"uuid":         pkgItem.UUID,
		})
	}
}

func (s *Server) upgradeReport(ctx *gin.Context) {
	buf := bytes.NewBuffer(nil)
	_, err := io.Copy(buf, ctx.Request.Body)
	if err != nil {
		s.log.Error("upgradeReport error", zap.Error(err))
		return
	}
	err = s.upgradeReportLog.Write(buf.Bytes())
	if err != nil {
		s.log.Error("upgradeReport write error", zap.Error(err))
	}
}
